#pragma once

#include <iostream>
#include <vector>
#include <semaphore.h>

const int defaultsize = 5;

template<class T>
class RingQueue
{
private:
    void P(sem_t &sem)
    {
        sem_wait(&sem);
    }

    void V(sem_t &sem)
    {
        sem_post(&sem);
    }

public:
    RingQueue(int size = defaultsize)
        :_size(size)
        ,_ringqueue(size)
        ,_p_step(0)
        ,_c_step(0)
    {
        sem_init(&_space_sem, 0, size);
        sem_init(&_data_sem, 0, 0);

        pthread_mutex_init(&_p_mutex, nullptr);
        pthread_mutex_init(&_c_mutex, nullptr);
    }

    // 生产
    void Push(const T &in)
    {
        P(_space_sem);
        pthread_mutex_lock(&_p_mutex);
        _ringqueue[_p_step] = in;
        _p_step++;
        _p_step %= _size;
        pthread_mutex_unlock(&_p_mutex);
        V(_data_sem);
    }

    // 消费
    void Pop(T *out)
    {   
        // 先申请信号量，再申请锁
        P(_data_sem);
        pthread_mutex_lock(&_c_mutex);
        *out = _ringqueue[_c_step];
        _c_step++;
        _c_step %= _size;
        pthread_mutex_unlock(&_c_mutex);
        V(_space_sem);
    }

    ~RingQueue()
    {
        sem_destroy(&_space_sem);
        sem_destroy(&_data_sem);

        pthread_mutex_destroy(&_p_mutex);
        pthread_mutex_destroy(&_c_mutex);
    }

private:
    int _size;
    std::vector<T> _ringqueue;
    int _p_step;     // 消费者位置
    int _c_step;     // 消费者位置
    sem_t _space_sem;   // 空间信号量，生产者申请
    sem_t _data_sem;    // 数据信号量，消费者申请

    pthread_mutex_t _p_mutex;     // 生产锁
    pthread_mutex_t _c_mutex;     // 消费锁
};